import React, {PureComponent} from "react";
import {
    View,
    Text,
    StyleSheet,
    AsyncStorage,
    ScrollView,
    DeviceEventEmitter,
    TouchableOpacity,
    ListView,
    Image,
    StatusBar,
    Dimensions
} from "react-native";
import RefreshListView, {RefreshState} from "react-native-refresh-list-view";
import {color} from "../../widget/color";
import api from "../../api/api";
import SelectGoodCourseCell from "../../widget/select/SelectGoodCourseCell";
import CourseDetailScene from "../detail/CourseDetailScene";
import method from "../../api/method";
import NetTool from "../../api/NetTool";
import SelectSubjectScrollTab from "../../widget/select/SelectSubjectScrollTab";
import EmptyCouponView from "../../widget/CommonEmptyView";
const {width} = Dimensions.get('window')
const {height} = Dimensions.get('window')
type Props = {
    navigation: any,
}

type State = {
    typeIndex: number,
    data: Array<Object>,
    refreshState: number,
}


class GoodCourseList extends PureComponent<Props, State> {

    constructor(props) {
        super(props)
        this.state = {
            typeIndex: 0,
            data: [],
            refreshState: RefreshState.Idle,
            subject: '',
            select_grade: 'primary_1',
            course_index: 0,
        }
    }

    componentDidMount() {


        let params = {
            subject: '',
            grade: 'primary_1',
            // is_hot: 1,
        }
        this.requestFirstPage(params)

        this.subjectEmitter = DeviceEventEmitter.addListener('subject', (item) => {
            let params = {
                subject: item,
                grade: this.state.select_grade,
                // is_hot: 1,
            }
            this.setState({subject: item.subject})
            this.requestFirstPage(params)
        });
        this.gradeEmitter = DeviceEventEmitter.addListener('grade', (item) => {
            let params = {
                subject: item.subject,
                grade: item.grade,
                // is_hot: 1,
            }
            this.setState({subject: item.subject, select_grade: item.grade, course_index: 0})
            this.requestFirstPage(params)
        });
        DeviceEventEmitter.addListener('loginIn', (args) => {
            let params = {
                subject: this.state.subject,
                grade: this.state.select_grade,
                // is_hot: 1,
            }
            this.requestFirstPage(params)
        });
        DeviceEventEmitter.addListener('loginOut', () => {
            let params = {
                subject: this.state.subject,
                grade: this.state.select_grade,
                // is_hot: 1,
            }
            this.requestFirstPage(params)
        });
    }

    componentWillUnmount() {
        this.gradeEmitter.remove();
        this.subjectEmitter.remove();
    }

    requestData = async(params) => {
        let json = await NetTool.fetchGetRequest(api.getCourseList, method.get, params)


        let dataList = json.courses.map((info) => {
            return {
                id: info.id,
                title: info.title,
                start_date: info.start_date,
                end_date: info.end_date,
                remains: info.remains,
                price: info.price,
                zhu_teacher: info.teachers[0],
                fu_teacher: info.teachers[1],
                tag: info.tag,
                subject: info.subject.charAt(0),
                buys:info.buys,
                totals:info.totals,
                amount:info.amount,
                discounts:info.discounts,
            }
        })
        return dataList
    }

    requestFirstPage = async(params) => {

        try {
            this.setState({refreshState: RefreshState.HeaderRefreshing})
            let dataList = await this.requestData(params)

            this.setState({
                data: dataList,
                refreshState: RefreshState.Idle,
            })
        } catch (error) {
            this.setState({
                refreshState: RefreshState.Failure,
            })
        }
    }

    requestNextPage = () => {

    }

    keyExtractor = (item: Object, index: number) => {
        return index + ''
    }

    renderCell = (rowData: any) => {
        return (
            <SelectGoodCourseCell
                info={rowData.item}
                onPress={this.onCellSelected}
            />
        )
    }

    onCellSelected = (info: Object) => {
        this.props.navigation.navigate('CourseDetailScene', {type: 0, info: info})
    }

    selectCourseTab(item) {
        this.setState({course_index: item})
    }

    render() {

        return (
            <View style={{flex:1,backgroundColor:'#f5f5f5',}}>
                <SelectSubjectScrollTab callbackSelect={(item)=>{this.selectCourseTab(item)}}
                                        index={this.state.course_index} subjects={['全部','数学','语文','英语']}/>

                    <RefreshListView
                        ListHeaderComponent={() => (
                    !this.state.data.length?
                    <EmptyCouponView height={(height-200)} tip={'没有找相关精品课'} source={require('../../../res/img/select/kecheng.png')}/>
                     : null)
                    }
                        style={styles.container}
                        data={this.state.data}
                        renderItem={this.renderCell}
                        keyExtractor={this.keyExtractor}
                        refreshState={this.state.refreshState}
                        onHeaderRefresh={()=>{this.requestFirstPage({
                        subject:this.state.subject,
                        grade:this.state.select_grade,
                        //is_hot:1,
                    })}}
                        onFooterRefresh={this.requestNextPage}
                        ItemSeparatorComponent={()=><View style={{width:width,height:10,backgroundColor:'#F9F9F9'}}/>}

                    />

            </View>
        )
    }
}


const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
        width: width,
        marginTop: 12
    },
})


export default GoodCourseList
